'''
Created on 2013-6-11

@author: ZuoPeng
'''
import fl.walkdirs
import codecs
import re
class sqlBatch(object):
    '''
    classdocs
    '''

    def __init__(self, sql_path):
        '''
        Constructor
        '''
        self.l = []
        self.ignore_l = []
        self.path = sql_path
        self.pat = r'(CRM|OM|RM|AA|PUB|SCP|TT)_(CREATE|ALTER|UPDATE)_(\d{8})_(\d{3})\S*\.SQL$'
                
    def append_f(self, f_name):
        if not f_name.upper().endswith('SQL'):
            print(f_name)
            return -1
        
        match = re.search(self.pat, f_name, re.I)
        if match:
            self.l.append(f_name)
        else:
            self.ignore_l.append(f_name)     
        
    def key_f(self, f_name):
        pat = self.pat
#         pat='(\d{8})/\S*'+self.pat
        match = re.search(pat, f_name, re.I)
        if not match:
            return 0
        
        if match.group(1).upper() == 'CRM':v = '1'
        if match.group(1).upper() == 'OM':v = '2'
        if match.group(1).upper() == 'RM':v = '3'
        if match.group(1).upper() == 'AA':v = '4'
        if match.group(1).upper() == 'TT':v = '5'
        if match.group(1).upper() == 'SCP':v = '6'
        if match.group(1).upper() == 'PUB':v = '7'
        
        if match.group(2).upper() == 'CREATE':v += '2'
        if match.group(2).upper() == 'ALTER':v += '3'
        if match.group(2).upper() == 'UPDATE':v += '5'
        v = v + str(match.group(3)) + str(match.group(4))
        return int(v)
    
    def create_batch_f(self, batch_f):
        fl.walkdirs.walk_dirs(self.path , self.append_f)
        f = codecs.open(batch_f, 'w')  # , encoding='utf-8')   
        
        f.write(r"spool d:\db.log;")
        f.write('\n\n')
          
        for f_name in self.ignore_l:
            f.write('#prompt loading ignore ' + f_name + ';\n')
#             f.write('@' + f_name + ';\n\n')             

        sorted_sql_f = sorted(self.l, key=self.key_f)

        for f_name in sorted_sql_f:
            f.write('prompt loading ' + f_name + ';\n')
            f.write('@' + f_name + ';\n\n') 
                   
        f.write('spool off;\n')
        f.close()

